package cn.mafangui.hotel.controller.common;

import cn.mafangui.hotel.entity.User;
import cn.mafangui.hotel.entity.Worker;
import cn.mafangui.hotel.enums.Role;
import cn.mafangui.hotel.response.AjaxResult;
import cn.mafangui.hotel.response.ResponseTool;
import cn.mafangui.hotel.service.UserService;
import cn.mafangui.hotel.service.WorkerService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Api(value = "注册",tags = "注册")
@Slf4j
@RestController
@RequestMapping(value = "/register")
public class RegisterController {

    @Autowired
    private UserService userService;
    @Autowired
    private WorkerService workerService;

    @PostMapping("/user")
    public AjaxResult userRegister(String username,String password,String name,String gender,String phone,String email,String address,String idcard){
        User user = new User(username,password,name,gender,phone,email,address,idcard);
        int result = 0;
        try{
            result = userService.insertUser(user);
        }catch (Exception e){
            // 如果因为用户名重复了不能插入数据库，则提示出来
            if(e.getMessage().contains("Duplicate entry")){
                return ResponseTool.failed("该用户名已注册，不允许重复注册");
            } else {
                log.error("注册报错xxx", e);
            }
        }
        if(result==1){
            return ResponseTool.success(result);
        }
        return ResponseTool.failed("注册失败,请稍后再试");
    }

    @PostMapping("/admin")
    public AjaxResult adminRegister(String username, String password, String name, String gender, String phone, String email, String address){
        Worker worker = new Worker(username,password,name,gender,phone,email,address);
        worker.setRole(Role.ADMIN.getValue());
        int result = workerService.insert(worker);
        if(result==1){
            return ResponseTool.success(result);
        }
        else {
            return ResponseTool.failed("注册失败,请稍后再试");
        }
    }

    @PostMapping("/operator")
    public AjaxResult operatorRegister(String username,String password,String name,String gender,String phone,String email,String address){
        Worker worker = new Worker(username,password,name,gender,phone,email,address);
        worker.setRole(Role.OPERATOR.getValue());
        int result = workerService.insert(worker);
        if(result==1){
            return ResponseTool.success(result);
        }
        else {
            return ResponseTool.failed("注册失败,请稍后再试");
        }
    }

}
